package com.easyjop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.easyjop.entity.constants.Constants;
import com.easyjop.entity.dto.ImportErrorItem;
import com.easyjop.entity.dto.SessionUserAdminDto;
import com.easyjop.entity.enums.*;
import com.easyjop.entity.po.Category;
import com.easyjop.entity.query.CategoryQuery;
import com.easyjop.exception.BusinessException;
import com.easyjop.mappers.ACommonMapper;
import com.easyjop.service.CategoryService;
import com.easyjop.utils.ExcelUtils;
import com.easyjop.utils.VerifyUtils;
import org.springframework.stereotype.Service;

import com.easyjop.entity.query.QuestionInfoQuery;
import com.easyjop.entity.po.QuestionInfo;
import com.easyjop.entity.vo.PaginationResultVO;
import com.easyjop.entity.query.SimplePage;
import com.easyjop.mappers.QuestionInfoMapper;
import com.easyjop.service.QuestionInfoService;
import com.easyjop.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 问题 业务接口实现
 */
@Service("questionInfoService")
public class QuestionInfoServiceImpl implements QuestionInfoService {

	@Resource
	private QuestionInfoMapper<QuestionInfo, QuestionInfoQuery> questionInfoMapper;
	@Resource
	private CategoryService categoryService;
	@Resource
	private ACommonMapper aCommonMapper;
	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<QuestionInfo> findListByParam(QuestionInfoQuery param) {
		return this.questionInfoMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(QuestionInfoQuery param) {
		return this.questionInfoMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<QuestionInfo> findListByPage(QuestionInfoQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<QuestionInfo> list = this.findListByParam(param);
		PaginationResultVO<QuestionInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(QuestionInfo bean) {
		return this.questionInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<QuestionInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.questionInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<QuestionInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.questionInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(QuestionInfo bean, QuestionInfoQuery param) {
		StringTools.checkParam(param);
		return this.questionInfoMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(QuestionInfoQuery param) {
		StringTools.checkParam(param);
		return this.questionInfoMapper.deleteByParam(param);
	}

	/**
	 * 根据QuestionId获取对象
	 */
	@Override
	public QuestionInfo getQuestionInfoByQuestionId(Integer questionId) {
		return this.questionInfoMapper.selectByQuestionId(questionId);
	}

	/**
	 * 根据QuestionId修改
	 */
	@Override
	public Integer updateQuestionInfoByQuestionId(QuestionInfo bean, Integer questionId) {
		return this.questionInfoMapper.updateByQuestionId(bean, questionId);
	}

	/**
	 * 根据QuestionId删除
	 */
	@Override
	public Integer deleteQuestionInfoByQuestionId(Integer questionId) {
		return this.questionInfoMapper.deleteByQuestionId(questionId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveQuestion(QuestionInfo bean, Boolean superAdmin) {
		QuestionInfo questionInfo = this.questionInfoMapper.selectByQuestionId(bean.getQuestionId());
		if (questionInfo == null) {
			/*新增问题*/
			bean.setCreateTime(new Date());
			this.questionInfoMapper.insert(bean);
		} else {
			/*更新*/
			{
				if (!bean.getQuestionId().equals(questionInfo.getQuestionId()) && !superAdmin) {
					throw new BusinessException(ResponseCodeEnum.CODE_902);
				}
				bean.setCreateUserId(null);
				bean.setCreateUserName(null);
				bean.setCreateTime(null);
				this.questionInfoMapper.updateByQuestionId(bean, bean.getQuestionId());
			}
		}
	}

	@Override
	public void delQuestionBatch(String s, Integer integer) {
		String[] delArrays=s.split(",");
		if (integer!=null){
			QuestionInfoQuery infoQuery = new QuestionInfoQuery();
			infoQuery.setQuestionIds(delArrays);
			List<QuestionInfo> questionInfoList = this.questionInfoMapper.selectList(infoQuery);
			List<QuestionInfo> collect = questionInfoList.stream().filter(a ->
					!a.getCreateUserId().equals(integer)).collect(Collectors.toList());
			if (!collect.isEmpty()){
				throw new BusinessException(ResponseCodeEnum.CODE_606);
			}
		}
		questionInfoMapper.deleteBatchByQuestionId(delArrays, PostStatusEnum.NO_POST.getStatus(), integer);

	}

	@Override
	public List<ImportErrorItem> importQuestion(MultipartFile file, SessionUserAdminDto userAdminDto) {
		List<Category> categoryList = categoryService.loadAllCategoryByQuery(CategoryTypeEnum.QUESTION.getType());
		Map<String, Category> chapterMap=categoryList.stream().collect(Collectors.
				toMap(Category::getCategoryName,
						Function.identity(),(data1, data2) -> data2));
		List<List<String>> dataList = ExcelUtils.readExcel(file, Constants.EXCEL_TITLE_QUESTION, Constants.ONE);
		//错误列表
		List<ImportErrorItem> errorList = new ArrayList<>();

		//问题列表
		List<QuestionInfo> questionList = new ArrayList<>();

		//数据行编号
		Integer dataRowNum = 2;
		for (List<String> row : dataList) {
			if (errorList.size() > Constants.LENGTH_50) {
				throw new BusinessException("错误数据超过" + Constants.LENGTH_50 + "行，请认真检查数据后再导入");
			}
			dataRowNum++;
			List<String> errorItemList = new ArrayList<>();
			Integer index = 0;
			//标题
			String title = row.get(index++);
			if (StringTools.isEmpty(title) || title.length() > Constants.LENGTH_150) {
				errorItemList.add("标题不能为空，且长度不能超过150");
			}
			//章节
			String chapterName = row.get(index++);
			Category chapter = chapterMap.get(chapterName);
			if (chapter == null) {
				errorItemList.add("该章节不存在");
			}
			//难度
			String difficultyLevel = row.get(index++);
			Integer difficultyLevelInt = null;
			if (!VerifyUtils.verify(VerifyRegexEnum.NUMBER_LETTER_UNDER_LINE, difficultyLevel)) {
				difficultyLevelInt = Integer.parseInt(difficultyLevel);
				if (difficultyLevelInt > 5) {
					errorItemList.add("难度只能是1到5的数字");
				}
			} else {
				errorItemList.add("难度必须是数字");
			}

			//问题描述
			String question = row.get(index++);
			String answerAnalysis = row.get(index++);
			if (StringTools.isEmpty(answerAnalysis)) {
				errorItemList.add("答案解析不能为空");
			}

			//有错误就继续
			if (errorItemList.size() > 0 || errorList.size() > 0) {
				ImportErrorItem errorItem = new ImportErrorItem();
				errorItem.setRowNum(dataRowNum);
				errorItem.setErrorItemList(errorItemList);
				errorList.add(errorItem);
				continue;
			}
			//封装对象
			QuestionInfo questionInfo = new QuestionInfo();
			questionInfo.setTitle(title);
			questionInfo.setCategoryId(chapter.getCategoryId());
			questionInfo.setCategoryName(chapter.getCategoryName());
			questionInfo.setDifficultyLevel(difficultyLevelInt);
			questionInfo.setQuestion(question);
			questionInfo.setAnswerAnalysis(answerAnalysis);
			questionInfo.setCreateTime(new Date());
			questionInfo.setStatus(PostStatusEnum.NO_POST.getStatus());
			questionInfo.setCreateUserId(String.valueOf(userAdminDto.getUserId()));
			questionInfo.setCreateUserName(userAdminDto.getUserName());
			questionList.add(questionInfo);
		}
		if (questionList.isEmpty()) {
			return errorList;
		}
		//插入数据库
		this.questionInfoMapper.insertBatch(questionList);
		return errorList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateStatus(String questionIds, Integer status) {
		QuestionInfo questionInfo = new QuestionInfo();
		questionInfo.setStatus(status);
		this.questionInfoMapper.updateByQuestionId(questionInfo,Integer.valueOf(questionIds));

	}

	@Override
	public QuestionInfo showDetailNext(QuestionInfoQuery query, Integer type, Integer currentId, Boolean updateReadCount) {
		if (type == null) {
			query.setQuestionId(currentId);
		} else {
			query.setNextType(type);
			query.setCurrentId(currentId);
		}
		QuestionInfo questionInfo = questionInfoMapper.showDetailNext(query);
		if (questionInfo == null && type == null) {
			throw new BusinessException("内容不存在");
		} else if (questionInfo == null && type == -1) {
			throw new BusinessException("已经是第一条了");
		} else if (questionInfo == null && type == 1) {
			throw new BusinessException("已经是最后一条了");
		}

		if (updateReadCount && questionInfo != null) {
			//更新阅读数
			aCommonMapper.updateCount(Constants.TABLE_NAME_QUESTION_INFO, 1, null, currentId);
			questionInfo.setReadCount(questionInfo.getReadCount() + 1);
		}
		return questionInfo;
	}
}